package com.ly.common.running.handler;

import com.ly.common.business.util.BusiUtil;
import com.ly.common.business.util.DateUtil;
import com.ly.common.running.dao.MybatisDao;
import com.ly.common.running.exception.BusinessException;
import com.ly.common.running.model.BaseInOut;
import com.ly.common.running.model.BusiInitFlowInfo;
import com.mysql.jdbc.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

/**
 * @author luoyana
 * @version V1.0
 * @ClassName BusiFlowExe
 * @description 幂等表登记
 * @update 2023/3/10
 */
@Service
@Transactional(propagation = Propagation.REQUIRES_NEW,rollbackFor = Exception.class)
public class BusiFlowExeHandler implements IPeHandler{
    @Resource
    MybatisDao mybatisDao;
    @Override
    public BaseInOut beforeHandle(BaseInOut in, String beanName) {
        BusiInitFlowInfo busiInitFlowInfo = new BusiInitFlowInfo();
        busiInitFlowInfo.setFlowNo(BusiUtil.getUUID());
        in.getSysHead().setServiceNo(busiInitFlowInfo.getFlowNo());
        busiInitFlowInfo.setBeanName(beanName);
        busiInitFlowInfo.setBeanCode(beanName);
        busiInitFlowInfo.setTranDate(BusiUtil.convertStr2Date(in.getSysHead().getTranDate()));
        busiInitFlowInfo.setSeqNo(in.getSysHead().getSeqNo());
        busiInitFlowInfo.setSubSeqNo(in.getSysHead().getSubSeqNo());
        //处理中
        busiInitFlowInfo.setStatus("P");
        busiInitFlowInfo.setStartTime(DateUtil.getDateTime("yyyy-MM-dd HH:mm:ss SSS"));
        mybatisDao.insert(busiInitFlowInfo);
        return null;
    }

    @Override
    public BaseInOut afterHandle(BaseInOut input, String flowName) {
        BusiInitFlowInfo busiInitFlowInfo = new BusiInitFlowInfo();
        busiInitFlowInfo.setFlowNo(input.getSysHead().getServiceNo());
        busiInitFlowInfo.setTranDate(BusiUtil.convertStr2Date(input.getSysHead().getTranDate()));
        BusiInitFlowInfo busiInitFlow = mybatisDao.selectOne(busiInitFlowInfo);
        if(BusiUtil.isNull(busiInitFlow)){
            throw new BusinessException("SC0001");
        }else {
            busiInitFlowInfo.setStatus(input.getSysHead().getRetStatus());
            busiInitFlowInfo.setEndTime(DateUtil.getDateTime("yyyy-MM-dd HH:mm:ss SSS"));
            mybatisDao.update(busiInitFlowInfo);
        }
        return null;
    }

    @Override
    public boolean isEffect() {
        return true;
    }
}
